// axios: 二次封装AJAX请求
// eslint-disable-next-line import/no-extraneous-dependencies
import axios from 'axios';
// eslint-disable-next-line import/no-extraneous-dependencies
import { ElMessage } from 'element-plus';
import router from '@/router/index';

class HttpRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
  }

  // 获取基本的配置
  getConfig() {
    return {
      baseURL: this.baseUrl,
      headers: {
        Authorization: localStorage.getItem('token')
      },
    };
  }

  // 拦截器
  // eslint-disable-next-line class-methods-use-this
  interceptors(instance) {
    // 添加请求拦截器
    instance.interceptors.request.use(
      (config) =>
        // 在发送请求前做些什么
        // eslint-disable-next-line implicit-arrow-linebreak
        config,
      (error) => {
        // 对请求错误做些什么
        ElMessage({
          type: 'error',
          message: '服务器暂未响应',
          grouping: true,
        });
        return Promise.reject(error.message);
      },
    );

    // 添加响应拦截器
    instance.interceptors.response.use(
      async (response) => {
        if (response.data.code == 500 && response.data.data?.message.search('TOKEN') != -1) {
          await router.push({path: '/login'})
          ElMessage({
            type: 'error',
            message: response.data.data.message,
            grouping: true,
          });
          return Promise.reject(response.data.message);
        }
        return  response.data
      },
      (error) => {
        return  error.response.data
      },
    )
  }

  sendRequest(options) {
    const instance = axios.create();
    // eslint-disable-next-line no-param-reassign
    options = { ...(this.getConfig()), ...options };
    this.interceptors(instance);
    return instance(options); // 返回Promise对象
  }
}

export default new HttpRequest('/api', router);
// export default new HttpRequest();
